<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h3>hello socket</h3>
    <p>【userId】：<div><input id="userId" name="userId" type="text" value="10"></div>
    <p>【toUserId】：<div><input id="toUserId" name="toUserId" type="text" value="20"></div>
    <p>【toUserId】：<div><input id="contentText" name="contentText" type="text" value="hello websocket"></div>
    <p>操作:<div><a onclick="openSocket()">开启socket</a></div>
    <p>【操作】：<div><a onclick="sendMsg()">发送消息</a></div>
</body>
<script>
    let socket;
    <!-- 建立连接 -->
    function openSocket(){
        if(typeof (WebSocket) == "undefined"){
            console.log("当前浏览器不支持WebSocket");
        }else{
            console.log("当前浏览器支持WebSocket");
            //建立连接
            let sid = document.getElementById('userId').value;
            let socketUrl = "ws://127.0.0.1:8088/websocket/" + sid;
            if(socket != null){
                socket.close();
                socket = null;
            }
            socket = new WebSocket(socketUrl);
            //打开事件
            socket.onopen = function () {
                console.log("WebSocket已连接");
            }
            //获得消息
            socket.onmessage = function (msg) {
                let serverMsg = "服务器：" + msg.data;
                console.log(serverMsg);
            }
            //关闭事件
            socket.onclose = function () {
                console.log("WebSocket已断开");
            }
            //错误事件
            socket.onerror = function () {
                console.log("WebSocket未知错误");
            }
        }
    }

    <!-- 发送消息 -->
    function sendMsg(){
        if(typeof (WebSocket) == "undefined"){
            console.log("当前浏览器不支持WebSocket");
        }else{
            console.log("当前浏览器支持WebSocket");
            let toUserId = document.getElementById('toUserId').value;
            let msgContent = document.getElementById('contentText').value;
            let msg = '{"toUserId":"'+toUserId+'","msgContent":"'+msgContent+'"}';
            socket.send(msg);
        }
    }
</script>
</html>